package cn.iocoder.yudao.adminserver.franky.LRU;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Description:
 * @Author: franky
 * @CreateDate: 2021/4/14 3:22 下午
 * @Version: 1.0
 */
public class LRUCacheEldest extends LinkedHashMap<Object, Object> {
    int capacity;

    public LRUCacheEldest(int capacity) {
        this.capacity = capacity;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<Object, Object> eldest) {
        return this.size() > this.capacity;
    }

    @Override
    public Object put(Object key, Object value) {
        remove(key);
        super.put(key, value);
        return value;
    }

    @Override
    public Object get(Object key) {
        if (containsKey(key)) {
            Object value = remove(key);
            this.put(key, value);
            return value;
        } else {
            return null;
        }
    }

    public static void main(String[] args) {
        LRUCacheEldest lruCache = new LRUCacheEldest(10);
        for (int i = 1; i < 11; i++) {
            lruCache.put(i, i);
        }
        System.out.println(lruCache);
        lruCache.put(1, 1);
        lruCache.put(12, 12);
        lruCache.put(13, 13);
        lruCache.put(null, 14);
        lruCache.put(15, null);
        lruCache.put(16, 16);
        System.out.println(lruCache);
        lruCache.get(6);
        lruCache.get(9);
        lruCache.get(null);
        lruCache.get(15);
        System.out.println(lruCache);
    }

}
